<template>
  <div>
    <KnHeader></KnHeader>
    <div class="chat-container">
      <div class="chat-messages scroll-container" id="chatContainer">
        <div v-for="(item,index) in chatList" :key="index">
          <!-- 用户消息 -->
          <div class="message-wrapper user" v-if="item.chatType === 'user'">
            <div class="message-content">
              <span class="text-bubble user">{{ item.content }}</span>
              <img class="user-avatar" src="../assets/logo.png" alt="用户头像">
            </div>
          </div>

          <!-- AI消息 -->
          <div class="message-wrapper ai" v-else>
            <img class="ai-avatar" src="../assets/logo.png" alt="AI头像">
            <span class="text-bubble ai" v-html="item.content"></span>
          </div>
        </div>
      </div>

      <div class="input-area">
        <input
            type="text"
            class="message-input"
            placeholder="输入消息..."
            v-model="inputValue"
            @keydown.enter="doChat"
        >
        <button class="send-button" @click="doChat">
          发送
          <svg class="send-icon" viewBox="0 0 24 24">
            <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>
          </svg>
        </button>
      </div>
    </div>
  </div>
</template>


<script>
import KnHeader from "@/components/KnHeader";
import {doChatB} from "@/apis/aiApi";
export default {
  components: {
    KnHeader
  },
  data() {
    return {
      userToken: '',
      currentUserName: '',
      userInfo: '',
      botMsgId: '',
      chatList: [],
      inputValue:''
    }
  },
  methods: {
    scrollToBottom() {
      const container = document.getElementById('chatContainer');
      container.scrollTop = container.scrollHeight;
      console.log('重新计算')
    },
    getUserToken() {
      let userToken = localStorage.getItem("token")
      console.log("userToken", userToken)
      this.userToken = userToken
      if (this.userToken === '' || this.userToken == null) {
        this.$message({
          type: 'error',
          message: '请登录后访问'
        })
      } else {
        let userInfo = this.$store.state.userInfo
        this.userInfo = userInfo
      }
    },
    initSSE(userName) {
      var me = this;

      let source = null;
      if (window.EventSource) {
        // 建立连接
        source = new EventSource('http://localhost:8087/sse/connect?userId=' + userName);
        console.log("连接用户=" + userName);
        me.currentUserName = userName;

        source.addEventListener('open', function (e) {
          console.log('建立连接');

          console.log("建立连接。。。");
        }, false);

        source.addEventListener('add', function (e) {
          console.log("add事件...");
          console.log(e.data);
          var receiveMsg = e.data;
          var botMsgId = me.botMsgId;
          if (botMsgId == null || botMsgId == '') {
            botMsgId = me.generateRandomId(12);
            me.botMsgId = botMsgId;
            console.log("botMsgId = " + botMsgId);

            // 为空，创建新对象
            var newBotContent = {
              id: "temp",
              content: receiveMsg,
              // time: '2023-05-01 12:00:00',
              userName: '文档助手',
              chatType: 'bot',
              botMsgId: botMsgId,
            };
            me.chatList.push(newBotContent);

          } else {
            console.log("botMsgId 不为空...");
            console.log("botMsgId = " + botMsgId);

            // 不为空，找到对应的聊天记录流式插入数据
            for (var i = 0; i < me.chatList.length; i++) {
              var chatItem = me.chatList[i];
              if (chatItem.botMsgId == botMsgId) {
                // 找到对应的聊天记录流式插入数据
                chatItem.content += receiveMsg;
              }
            }
          }

          // me.scrollToBottom();
          me.scrollToBottom()
        });

        source.addEventListener('finish', function (e) {
          console.log("finish事件...");
          me.botMsgId = null;
        });

        source.addEventListener('error', function (e) {
          console.log("error事件...");
          console.log("e.readyState: " + source.readyState);

          if (e.readyState === EventSource.CLOSED) {
            console.log('connection is closed');
          } else {
            console.log("Error occured", event);
          }
          // close方法用于关闭连接
          source.close();
        });

        source.addEventListener("customEvent", function(e) {
          console.log(e.lastEventId);
          console.log(e.data);
        }, false);
      } else {
        console.log("浏览器不支持SSE");
      }
    },

    submitUserName() {
      let userName = this.userInfo.username
      // alert('用户名: ' + userName);
      // 在这里可以添加更多的逻辑来处理用户名
      // this.currentUserName = userName;
      this.initSSE(userName);
    },

    getChatRecords(who) {
      var me = this;
      doctorApi.getRecords(who).then((result) => {
        console.log(result);
        this.chatList = result;

        me.scrollToBottom();
      }).catch((err) => {

      });
    },

    handleKeyDown(event) {
      if (event.key === 'Enter') {
        this.doChat();
      }
    },

    doChat() {
      var currentUserName = this.currentUserName;

      const userInput = this.inputValue
      var pendingMsg = userInput.trim();
      if (pendingMsg === '') return;

      if (currentUserName == null || currentUserName == '') {
        alert('请输入沟通用户名');
        return;
      }

      // 发送消息到后端
      var singleChat = {
        currentUserName: currentUserName,
        message: pendingMsg
      };

      doctorApi.doChat(singleChat);

      var newUserContent = {
        content: pendingMsg,
        userName: currentUserName,
        chatType: 'user',
      }
      this.chatList.push(newUserContent);

      this.inputValue = ''
      this.scrollToBottom()
    },

    generateRandomId(length) {
      const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
      let result = '';
      const charactersLength = characters.length;
      for (let i = 0; i < length; i++) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
      }
      return result;
    },

  },
  props: {},
  created() {
    var me = this
    this.getUserToken()
    this.submitUserName()
    this.getChatRecords(this.userInfo.username)
  },
  mounted() {
  }
}
</script>

<style scoped>
.chat-container {
  max-width: 800px;
  margin: 20px auto;
  background: #f8f9fa;
  border-radius: 12px;
  box-shadow: 0 2px 15px rgba(0, 0, 0, 0.1);
}

.chat-messages {
  height: 65vh;
  padding: 20px;
  background: #f8f9fa;
  overflow-y: auto;

}

.message-wrapper {
  margin: 15px 0;
  display: flex;
  align-items: start;
}

.message-wrapper.user {
  justify-content: flex-end;
}

.text-bubble {
  max-width: 70%;
  padding: 12px 18px;
  border-radius: 18px;
  line-height: 1.5;
  position: relative;
  word-break: break-word;
}

.user .text-bubble {
  background: #3a7cff;
  color: white;
  border-radius: 18px 4px 18px 18px;
  margin-left: 40px;
}

.ai .text-bubble {
  background: white;
  color: #2d3748;
  border-radius: 4px 18px 18px 18px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.user-avatar, .ai-avatar {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  flex-shrink: 0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.input-area {
  display: flex;
  gap: 12px;
  padding: 20px;
  background: white;
  border-top: 1px solid #e9ecef;
}

.message-input {
  flex: 1;
  padding: 12px 16px;
  border: 1px solid #dee2e6;
  border-radius: 8px;
  font-size: 16px;
  transition: all 0.3s ease;
}

.message-input:focus {
  outline: none;
  border-color: #3a7cff;
  box-shadow: 0 0 0 3px rgba(58, 124, 255, 0.1);
}

.send-button {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 12px 20px;
  background: #3a7cff;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.send-button:hover {
  background: #2c6adf;
  transform: translateY(-1px);
}

.send-icon {
  width: 18px;
  height: 18px;
  fill: currentColor;
}

/* 自定义滚动条 */
.scroll-container::-webkit-scrollbar {
  width: 8px;
}

.scroll-container::-webkit-scrollbar-track {
  background: #f1f3f5;
  border-radius: 4px;
}

.scroll-container::-webkit-scrollbar-thumb {
  background: #ced4da;
  border-radius: 4px;
}

.scroll-container::-webkit-scrollbar-thumb:hover {
  background: #adb5bd;
}
</style>